<?php
/**
 * Created by IntelliJ IDEA.
 * User: jjj
 * Date: 2018/4/2
 * Time: 16:33
 */

function gmt_iso8601($time) {
	$dtStr = date("c", $time); //格式为2016-12-27T09:10:11+08:00
	$mydatetime = new \DateTime($dtStr);
	$expiration = $mydatetime->format(\DateTime::ISO8601); //格式为2016-12-27T09:12:32+0800
	$pos = strpos($expiration, '+');
	$expiration = substr($expiration, 0, $pos);//格式为2016-12-27T09:12:32
	return $expiration."Z";
}

function oss_policy(string $type, int $maxsize = 500*1024*1024) {

	$dir = $type; // 上传目录

	$bucket = 'zq-server';
	// 计算过期时间
	$end = time() + 30;
	// 生成ISO8601格式时间
	$expiration = gmt_iso8601($end);

	$conditions = [];
	$conditions[] = [0=>'content-length-range', 1=>0, 2=>$maxsize]; // 最大文件大小.用户可以自己设置 100M

	$start = [0=>'starts-with', 1=>'$key', 2=>$dir]; //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
	$conditions[] = $start;

	$arr = ['expiration'=>$expiration,'conditions'=>$conditions];
	$policy = json_encode($arr);
	$base64_policy = base64_encode($policy);
	$string_to_sign = $base64_policy;
	$signature = base64_encode(hash_hmac('sha1', $string_to_sign, 'p2X5SvXjBNqplRNb6Ed599Ojn19q4S', true));

	$response = [];
	$response['policy'] = $base64_policy;
	$response['OSSAccessKeyId'] = 'LTAIQNaWgXLwnH1n';
	$response['signature'] = $signature;
	$response['expire'] = $end;
	$response['dir'] = $dir;  //这个参数是设置用户上传指定的前缀
	$response['host'] = 'http://'.$bucket.'.'. 'oss-cn-shanghai.aliyuncs.com';
	$response['dns'] = 'http://image.cloud.zqcj.net.cn';

	return $response;
}

$response = oss_policy('editor', 512*1024);
header('content-type:application/json');
echo json_encode($response);
